﻿namespace MonetDbDataProvider
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Linq;

    using MonetDbDataProvider.Extensions;

    public class MonetDbParameterCollection : List<MonetDbParameter>, IDataParameterCollection
    {
        public int Add(object value)
        {
            this.ValidateParameterType((MonetDbParameter)value);

            base.Add((MonetDbParameter)value);

            return base.IndexOf((MonetDbParameter)value);
        }

        public bool Contains(string parameterName)
        {
            return this.Any(p => p.ParameterName == parameterName);
        }

        public int IndexOf(string parameterName)
        {
            return this.FindIndex(p => p.ParameterName == parameterName);
        }

        public void RemoveAt(string parameterName)
        {
            var index = this.IndexOf(parameterName);

            if(index > -1)
                this.RemoveAt(index);
        }

        public object this[string parameterName]
        {
            get
            {
                return this.FirstOrDefault(p => p.ParameterName == parameterName);
            }
            set
            {
                this[IndexOf(parameterName)] = (MonetDbParameter)value;
            }
        }

        private void ValidateParameterType(MonetDbParameter monetDbParameter)
        {
            // TODO: Need to add more validation

            if (monetDbParameter == null)
                throw new ArgumentNullException("monetDbParameter", "MonetDbParameter object must not be null");

            if (this.Any(param => param.ParameterName == monetDbParameter.ParameterName))
            {
                throw new ArgumentException("MonetDbParameter with name already exists. Names must be unique.");
            }

            try
            {
                TypeDescriptor.GetConverter(monetDbParameter.DbType.ToSystemType()).ConvertFrom(monetDbParameter.Value);
            }
            catch (Exception ex)
            {
                throw new FormatException("MonetDbParameter value cannot be converted to type", ex.InnerException);
            }


            if (monetDbParameter.DbType == DbType.String && monetDbParameter.Size > 0)
            {
                if (Convert.ToString(monetDbParameter.Value).Length > monetDbParameter.Size)
                    throw new ArgumentException("MonetDbParameter value is greater than specified size", "monetDbParameter");
            }
        }
    }
}
